﻿using log4net;
using Ma.Bussiness.ConfigExtend;
using MRO.ClientApplication.Models.BaiYa;
using MRO.ClientApplication.ModelsDto.Response;
using MRO.ClientApplication.Util;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;

namespace MRO.ClientApplication.BaseClient
{
    public static class BaiYaClient
    {
        private static readonly ILog logger = LogManager.GetLogger(typeof(BaiYaClient));
        /// <summary>
        /// 获取Token
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        static string GetToken()
        {
            try
            {
                if (CacheHelper.GetCache("BY_Token") == null)
                {
                    var TokenOutput = HttpHelper.PostGetToken<BYGetTokenResponse>(StaticField.BaiYa_GetTokenPost);
                    CacheHelper.SetCache("BY_Token", $"Bearer {TokenOutput.Access_token}", TokenOutput.Expires_in);
                }
                return CacheHelper.GetCache("BY_Token").ToString() ?? "";
            }
            catch (Exception ex)
            {
                logger.Error($"10011:MethodName={System.Reflection.MethodBase.GetCurrentMethod().Name};Msg:{ex.Message}");
                throw;
            }

        } 

        public static string PostWithToken(string url, object obj=null)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                var tonken = GetToken();
                request.Headers.Add("Authorization", tonken);
                return HttpHelper.Post(request, obj);
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format($"URL={url};Msg={ex.Message}"));
            }
        }
       
        public static T PostWithToken<T>(string url, object obj=null)
        {
            try
            {
                var tonken = GetToken();
                Dictionary<string, string> pairs = new Dictionary<string, string>()
                {
                    { "Authorization", tonken }
                };
                var res = HttpHelper.PostByHeader<ResponseResult<T>>(url, obj, pairs);
                if (res.Code== 200)
                {
                    return res.Data;
                }
                else
                {
                    throw new Exception($" Code={res.Code};消息:{res.Msg}");
                }
            }
            catch (HttpRequestException httpEx)
            {
                logger.Error($"10014: URL={url};Msg=" + httpEx.Message, httpEx);
                throw new Exception($"10014:请求接口失败{httpEx.Message}");
            }
            catch (Exception ex)
            {
                logger.Error($"10012:URL={url};Msg={ex.Message}");
                logger.Error($"Data:{JsonConvert.SerializeObjectAsync(obj)}");
                throw new Exception(string.Format($"10012:{ex.Message}"));
            }
        }
    }
}
